<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('su.product.code')" prop="code">
        <el-input v-model="formData.code" :placeholder="t('common.inputText') + t('su.product.code')" />
      </el-form-item>
      <el-form-item :label="t('su.product.code')" prop="code">
        <el-select v-model="formData.type" placeholder="choose type">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SU_PRODUCT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('su.product.category')" prop="categoryId">
        <el-select v-model="formData.categoryId" :placeholder="t('common.inputText') + t('su.product.category')">
          <el-option
            v-for="category in categorys"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('su.product.brand')" prop="brandId">
        <el-select v-model="formData.brandId" :placeholder="t('common.inputText') + t('su.product.brand')">
          <el-option
            v-for="brand in brands"
            :key="brand.id"
            :label="brand.name"
            :value="brand.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('su.product.unit')" prop="unit">
        <el-select v-model="formData.unit" :placeholder="t('common.inputText') + t('su.product.unit')">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SU_PRODUCT_UNIT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('su.product.pic')" prop="picUrl">
        <UploadImg v-model="formData.picUrl" />
      </el-form-item>
      <el-form-item :label="t('su.product.material')" prop="material">
        <el-select v-model="formData.material" :placeholder="t('common.inputText') + t('su.product.material')">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SU_PRODUCT_MATERIAL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('su.product.laser')" prop="laser">
        <el-select v-model="formData.laser" :placeholder="t('common.inputText') + t('su.product.laser')">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SU_PRODUCT_LASER)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('su.product.polish')" prop="polish">
        <el-select v-model="formData.polish" :placeholder="t('common.inputText') + t('su.product.polish')">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SU_PRODUCT_POLISH)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('su.product.dyed')" prop="dyed">
        <el-select v-model="formData.dyed" :placeholder="t('common.inputText') + t('su.product.dyed')">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SU_PRODUCT_DYED)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('su.product.finishing')" prop="finishing">
        <el-select v-model="formData.finishing" :placeholder="t('common.inputText') + t('su.product.finishing')">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SU_PRODUCT_FINISHING)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('su.product.keyword')" prop="keyword">
        <el-input v-model="formData.keyword" :placeholder="t('common.inputText') + t('su.product.keyword')" />
      </el-form-item>
      <el-form-item :label="t('su.product.introduction')" prop="introduction">
        <el-input v-model="formData.introduction" :placeholder="t('common.inputText') + t('su.product.introduction')" />
      </el-form-item>

<!--      <el-form-item label="商品轮播图地址数组，以逗号分隔最多上传15张" prop="sliderPicUrls">-->
<!--        <UploadFile v-model="formData.sliderPicUrls" />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="商品视频" prop="videoUrl">-->
<!--        <UploadFile v-model="formData.videoUrl" />-->
<!--      </el-form-item>-->
      <el-form-item :label="t('su.product.status')" prop="status">
        <el-select v-model="formData.status" :placeholder="t('common.inputText') + t('su.product.status')">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SU_PRODUCT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('common.ok') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { ProductApi, ProductVO } from '@/api/su/product'
import {CommonApi} from "@/api/su/common";

/** 商品 表单 */
defineOptions({ name: 'ProductForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const categorys = ref([])
const brands = ref([])
const getCategory = async () => {
  const data = await CommonApi.getCategoryList()
  categorys.value = data
  if (!formData.value.id) {
    categorys.value.forEach(category => {
      if (category.defaultStatus) {
        formData.value.categoryId = category.id
      }
    })
  }
}

const getBrand = async () => {
  const data = await CommonApi.getBrandList()
  brands.value = data
}

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  type: undefined,
  picUrl: undefined,
  material: undefined,
  laser: undefined,
  polish: undefined,
  dyed: undefined,
  finishing: undefined,
  keyword: undefined,
  introduction: undefined,
  categoryId: undefined,
  brandId: undefined,
  sliderPicUrls: undefined,
  videoUrl: undefined,
  unit: undefined,
  status: undefined
})
const formRules = reactive({
  code: [{ required: true, message: t('su.product.code')+t('validate.notempty'), trigger: 'blur' }],
  categoryId: [{ required: true, message: t('su.product.category')+t('validate.notempty'), trigger: 'change' }],
  unit: [{ required: true, message: t('su.product.unit')+t('validate.notempty'), trigger: 'change' }],
  status: [{ required: true, message: t('su.product.status')+t('validate.notempty'), trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formData.value.id = id
  }
  getCategory()
  getBrand()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProductApi.getProduct(id)
    } finally {
      formLoading.value = false
    }
  } else {
    formData.value.unit = 'Button'
    formData.value.status = 0
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProductVO
    if (formType.value === 'create') {
      await ProductApi.createProduct(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProductApi.updateProduct(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    picUrl: undefined,
    material: undefined,
    laser: undefined,
    polish: undefined,
    dyed: undefined,
    finishing: undefined,
    keyword: undefined,
    introduction: undefined,
    categoryId: undefined,
    brandId: undefined,
    sliderPicUrls: undefined,
    videoUrl: undefined,
    unit: undefined,
    status: undefined
  }
  formRef.value?.resetFields()
}
</script>
